package com.smartens.boit.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.RecyclerView;

import com.smartens.boit.R;
import com.smartens.boit.activity.ControlActivity;
import com.smartens.boit.bean.ControlBean;
import com.smartens.boit.fragment.ManualControlFragment;
import com.smartens.boit.fragment.viewmode.ManualControlViewmode;
import com.smartens.boit.util.EditTextUtil;
import com.smartens.boit.util.HttpHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description 手动控制适配器
 * @Author songtt
 * @Date 2021/3/4
 */

public class ManualAdapter extends RecyclerView.Adapter<ManualAdapter.ViewHolder> {
    public boolean ischeck;
    private List<ControlBean> mList;
    private HttpHelper helper;
    private Context context;
    private Boolean isManual = false;
    //private Boolean isRefresh = false;
    private int mode = 0;
    private boolean oneclose;
    private boolean twoclose;
    private volatile boolean isok = true;
    Fragment fragment;
    ManualControlViewmode viewmode;
    private boolean isseek = false;
    private boolean resetEdit;

    public ManualAdapter(List<ControlBean> list, Fragment fragment) {
        mList = list;
        this.fragment = fragment;
        viewmode = new ViewModelProvider(fragment, ViewModelProvider.AndroidViewModelFactory.getInstance(fragment.getActivity().getApplication())).get(ManualControlViewmode.class);
        helper = HttpHelper.getInstance();
        Log.v("asdsadsadasd", "ManualAdapter");
        SetGroupLight("1", viewmode.getList().getValue().get(0).getLight() + "");
        SetGroupLight("2", viewmode.getList().getValue().get(1).getLight() + "");
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //将我们自定义的item布局R.layout.item_one转换为View
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_manual, parent, false);
        //将view传递给我们自定义的ViewHolder
        ViewHolder holder = new ViewHolder(view);
        //返回这个MyHolder实体

        return holder;
    }

    /**
     * 通过方法提供的ViewHolder，将数据绑定到ViewHolder中
     *
     * @param holder
     * @param position
     */
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

        holder.name.setText(mList.get(holder.getAdapterPosition()).getName());
        // holder.checkBox.setChecked(mList.get(position).getOpen());
        holder.seekBar.setProgress(mList.get(holder.getAdapterPosition()).getLight());
        holder.seekBar.setMax(100);
        holder.editText.setText(mList.get(holder.getAdapterPosition()).getLight() + "");
    /*    holder.editText.addTextChangedListener(new TextWatcher() {
            private String outStr = "";

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                Log.v("dfsdfsdfdsfsdf", "beforeTextChanged");
                String edit = s.toString();
                if (edit.length() == 2 && Integer.parseInt(edit) >= 10) {
                    outStr = edit;
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Log.v("dfsdfsdfdsfsdf", "onTextChanged");
                String words = s.toString();
                //首先内容进行非空判断，空内容（""和null）不处理
                if (!TextUtils.isEmpty(words)) {
                    //1-100的正则验证
                    Pattern p = Pattern.compile("^(100|[1-9]\\d|\\d)$");
                    Matcher m = p.matcher(words);
                    if (m.find() || ("").equals(words)) {
                        //这个时候输入的是合法范围内的值
                    } else {
                        if (words.length() > 2) {
                            //若输入不合规，且长度超过2位，继续输入只显示之前存储的outStr
                            holder.editText.setText(outStr);
                            //重置输入框内容后默认光标位置会回到索引0的地方，要改变光标位置

                        }
                        Toast.makeText(fragment.getActivity(), "请输入范围在1-100之间的整数", Toast.LENGTH_SHORT).show();
                    }

                }

            }

            @Override
            public void afterTextChanged(Editable s) {
                Log.v("dfsdfsdfdsfsdf", "afterTextChanged");
                //holder.editText.setText(litedata+"");
                String words = s.toString();
                if (!TextUtils.isEmpty(words)) {
                    if (Integer.parseInt(s.toString()) > 100) {
                        holder.editText.setText("100");
                        Toast.makeText(fragment.getActivity(), "请输入范围在1-100之间的整数", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    holder.editText.setText("0");
                }
                int i = Integer.parseInt(holder.editText.getText().toString());
                holder.seekBar.setProgress(i);
                List<ControlBean> list = viewmode.getList().getValue();
                list.get(holder.getAdapterPosition()).setLight(i);
                viewmode.getList().setValue(list);
                if (!isseek) {
                    // SetGroupLight(String.valueOf(holder.getAdapterPosition() + 1), String.valueOf(i));
                }
                holder.editText.setSelection(s.length());
            }
        });*/
        holder.editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE&&!TextUtils.isEmpty(v.getText().toString())) {
                    int i = Integer.parseInt(v.getText().toString());
                    if (i < 0) {
                        i = 0;
                        Toast.makeText(fragment.getContext(), "请输入0到100的数值", Toast.LENGTH_SHORT).show();
                    }
                    if (i > 100) {
                        i = 100;
                        Toast.makeText(fragment.getContext(), "请输入0到100的数值", Toast.LENGTH_SHORT).show();
                    }
                    SetGroupLight(String.valueOf(holder.getAdapterPosition() + 1), i + "");
                    holder.seekBar.setProgress(i);
                    holder.editText.setText(String.valueOf(i));
                    List<ControlBean> list = viewmode.getList().getValue();
                    list.get(holder.getAdapterPosition()).setLight(i);
                    viewmode.getList().setValue(list);
                }
                return false;
            }
        });
        setLinVisible(holder, !viewmode.getIsshoudong().getValue());
        holder.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                Log.v("ssdfsdfsdfsdf", "onProgressChanged");
                List<ControlBean> list = viewmode.getList().getValue();
                list.get(holder.getAdapterPosition()).setLight(progress);
                viewmode.getList().setValue(list);
                holder.editText.setText(String.valueOf(progress));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

                isseek = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                SetGroupLight(String.valueOf(holder.getAdapterPosition() + 1), String.valueOf(seekBar.getProgress()));
            }
        });
    }

    public void setManual(Boolean isManual) {
        this.isManual = isManual;
    }

    /**
     * 获取数据源总的条数
     *
     * @return
     */
    @Override
    public int getItemCount() {
        return mList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        CheckBox checkBox;
        SeekBar seekBar;
        LinearLayout linearLayout1;
        LinearLayout linearLayout2;
        LinearLayout linearLayout3;
        TextView name;
        EditText editText;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            checkBox = itemView.findViewById(R.id.sw_check);
            seekBar = itemView.findViewById(R.id.seek_bar);
            linearLayout1 = itemView.findViewById(R.id.lin_seek);
            linearLayout2 = itemView.findViewById(R.id.lin_seek_add);
            linearLayout3 = itemView.findViewById(R.id.linearlayout3);
            name = itemView.findViewById(R.id.tv_name);
            editText = itemView.findViewById(R.id.showLiteEdit);
            editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    Log.v("myeditTextaaa", hasFocus + "");
                    if (!hasFocus) {
                        int light = viewmode.getList().getValue().get(getAdapterPosition()).getLight();
                        editText.setText(light + "");
                    }
                }
            });
        }
    }


    /**
     * 设置亮度
     *
     * @param groupNumber mac编号
     * @param value       亮度值
     */
    public void SetGroupLight(String groupNumber, String value) {
        Log.v("dfsfsdfsdfsd11", groupNumber + "---" + value);
        helper.SetGroupLight(groupNumber, value, new HttpHelper.HttpCallBack<String>() {

            @Override
            public void onSuccess(List<String> result) {
                synchronized (ManualAdapter.class) {
                    //     Log.v("====SetGroupLight=切换成功", result.get(0));
                    Log.v("dfsfsdfsdfsd", "ok2");
                }
            }

            @SuppressLint("LongLogTag")
            @Override
            public void onFailure(final String message) {
                synchronized (ManualAdapter.class) {
                    //   Log.v("=====SetGroupLight==onFailure", message);
                    Log.v("dfsfsdfsdfsd", "ok2");
                }

            }
        });
    }

    public void setLinVisible(ViewHolder holder, boolean isgone) {
        if (!isgone) {
            holder.linearLayout1.setVisibility(View.VISIBLE);
            holder.linearLayout2.setVisibility(View.VISIBLE);
            holder.linearLayout3.setVisibility(View.VISIBLE);
        } else {
            holder.linearLayout1.setVisibility(View.GONE);
            holder.linearLayout2.setVisibility(View.GONE);
            holder.linearLayout3.setVisibility(View.GONE);
        }
    }

}
